import React from "react";
import {
    Form,
    Select,
    InputNumber,
    Switch,
    Radio,
    Slider,
    Button,
    Upload,
    Icon,
    Rate,
    Checkbox,
    Row,
    Col,
    Breadcrumb,
    Input,
    Modal,
    message
} from 'antd';
import CustomLayout from "../../../components/CustomLayout/customLayout";
import menuList from "../../../utils/staticVariable";
import {_queryProductInfoAllIdNoName, _addPictureAlbum} from "../../../utils/apiList";

const {Option} = Select;
const {TextArea} = Input;
const {Search} = Input;

function getBase64(file) {
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => resolve(reader.result);
        reader.onerror = error => reject(error);
    });
}

const CollectionCreateForm = Form.create({name: 'form'})(
    class extends React.Component {
        state = {
            previewVisible: false,
            previewImage: '',
            previewTitle: '',
            fileList: [],
            fileNameList: [],
            options: [],
        };

        componentDidMount() {
            this.getOptions();
        }

        handleSubmit = e => {
            e.preventDefault();
            const {form, history} = this.props;
            form.validateFields((err, values) => {
                if (!err) {
                    const params = values;
                    params.picturecover = this.state.fileNameList.join(',');
                    params.relatedproducts= params.relatedList.join(',');
                    _addPictureAlbum(params).then((res) => {
                        if (res.data.success) {
                            message.success(<b>新增画册成功</b>, 3);
                            history.push('/tianyi/catalogList');
                        } else {
                            message.error(<b>{res.data.msg}</b>, 3);
                        }
                    }).catch(error => {
                        message.error(<b>请求失败！</b>, 3);
                    });
                    console.log(params);
                }
            });
        };

        handleCancel = () => this.setState({previewVisible: false});

        handlePreview = async file => {
            if (!file.url && !file.preview) {
                file.preview = await getBase64(file.originFileObj);
            }

            this.setState({
                previewImage: file.url || file.preview,
                previewVisible: true,
                previewTitle: file.name || file.url.substring(file.url.lastIndexOf('/') + 1),
            });
        };

        handleChange = (info) => {
            const {file, fileList} = info;
            const {fileNameList} = this.state;
            this.setState({fileList});
            if (file.status === 'done') {
                message.success(`${file.name} 上传成功.`);
                const fileName = file.response.data;
                this.setState({fileNameList: [...fileNameList, fileName]})

            } else if (file.status === 'error') {
                message.error(`${file.name} 上传失败.`);
            }

        };

        getOptions = () => {
            _queryProductInfoAllIdNoName().then((res) => {
                if (res.data.success) {
                    const productList = res.data.data ? res.data.data : [];
                    const options = productList.map(d => <Option
                        key={d.id.toString()}><b>{d.productNo}</b><span>{d.productName}</span></Option>);
                    this.setState({options});
                } else {
                    message.error(<b>{res.data.msg}</b>, 3);
                }
            }).catch(error => {
                message.error(<b>请求失败！</b>, 3);
            });
        };

        render() {
            const {getFieldDecorator} = this.props.form;
            const {previewVisible, previewImage, fileList, previewTitle, options} = this.state;
            const uploadButton = (
                <div style={{marginTop: 8}}>点击上传</div>
            );
            return (
                <Form layout="vertical" onSubmit={this.handleSubmit}>
                    <Row gutter={16}>
                        <Col span={24}>
                            <Form.Item label="画册名称">
                                {getFieldDecorator('albumname', {
                                    rules: [{required: true, message: '请输入画册名称!'}],
                                })(
                                    <Input/>,
                                )}
                            </Form.Item>
                        </Col>
                    </Row>
                    <Row gutter={16}>
                        <Col span={12}>
                            <Form.Item label="对接人">
                                {getFieldDecorator('contactperson', {
                                    rules: [{required: true, message: '请输入对接人!'}],
                                })(
                                    <Input/>,
                                )}
                            </Form.Item>
                        </Col>
                        <Col span={12}>
                            <Form.Item label="对接人手机号">
                                {getFieldDecorator('contactpersonphone', {
                                    rules: [{required: true, message: '请输入对接人手机号!'}],
                                })(
                                    <Input/>,
                                )}
                            </Form.Item>
                        </Col>
                    </Row>
                    <Row gutter={16}>
                        <Col span={12}>
                            <Form.Item label="对接人微信号">
                                {getFieldDecorator('contactpersonwechat', {
                                    rules: [{required: true, message: '请输入对接人微信号!'}],
                                })(
                                    <Input/>,
                                )}
                            </Form.Item>
                        </Col>
                        <Col span={12}>
                            <Form.Item label="对接人邮箱">
                                {getFieldDecorator('contactpersonemail', {
                                    rules: [{required: true, message: '请输入对接人邮箱!'}],
                                })(
                                    <Input/>,
                                )}
                            </Form.Item>
                        </Col>
                    </Row>
                    <Row gutter={16}>
                        <Col span={24}>
                            <Form.Item label="画册展示图">
                                <Upload
                                    action="/photo/uploadPhoto"
                                    listType="picture-card"
                                    fileList={fileList}
                                    onPreview={this.handlePreview}
                                    onChange={this.handleChange}
                                >
                                    {fileList.length >= 8 ? null : uploadButton}
                                </Upload>
                                <Modal
                                    visible={previewVisible}
                                    title={previewTitle}
                                    footer={null}
                                    onCancel={this.handleCancel}
                                    centered
                                    bodyStyle={{maxHeight: '80vh', overflow: 'scroll'}}
                                >
                                    <img alt="example" style={{width: '100%'}} src={previewImage}/>
                                </Modal>
                            </Form.Item>
                        </Col>
                    </Row>
                    <Row gutter={16}>
                        <Col span={24}>
                            <Form.Item label="画册描述">
                                {getFieldDecorator('albumdescription', {
                                    rules: [{required: true, message: '请输入画册描述!'}],
                                })(
                                    <TextArea rows={4}/>
                                )}
                            </Form.Item>
                        </Col>
                    </Row>
                    <Row gutter={16}>
                        <Col span={24}>
                            <Form.Item label="关联商品">
                                {getFieldDecorator('relatedList')(
                                    <Select mode="multiple">{options}</Select>
                                )}
                            </Form.Item>
                        </Col>
                    </Row>
                    <Button type="primary" htmlType="submit">
                        提交
                    </Button>

                </Form>
            );
        }
    });

class CatalogUpload extends React.Component {

    render() {
        return (
            <CustomLayout>
                <Breadcrumb style={{margin: '16px 0'}}>
                    <Breadcrumb.Item>品牌与产品管理</Breadcrumb.Item>
                    <Breadcrumb.Item>画册上传</Breadcrumb.Item>
                </Breadcrumb>
                <div className={'App-Section'}>
                    <CollectionCreateForm history={this.props.history}/>
                </div>
            </CustomLayout>
        );
    }
}

export default CatalogUpload;